// pages/products/products.ts
import { MerchantAPI } from '../../utils/api'

interface Product {
  productId: number;
  productName: string;
  imageUrl: string;
  description: string;
  marketPrice: number;
  regionPrice: number;
  stockQuantity: number;
  salesCount: number;
  monthlySales: number;
  status: number;
  statusText: string;
  auditStatus: number;
  auditStatusText: string;
  categoryId: number;
  categoryName: string;
  isHot: boolean;
  isNew: boolean;
  sortOrder: number;
  createdAt: string;
  skuList?: any[];
  specGroups?: any[];
  hasMultipleSkus?: boolean;
  parsedSpecGroups?: Array<{ groupName: string; specOptions: string[] }>;
  canToggleStatus?: boolean;
}

const STATUS_TEXT_MAP: Record<number, string> = {
  0: '已下架',
  1: '售卖中',
  2: '已售罄'
};

const AUDIT_STATUS_TEXT_MAP: Record<number, string> = {
  0: '待审核',
  1: '审核通过',
  2: '审核未通过'
};

interface ProductsPageData {
  hasLogin: boolean;
  loading: boolean;
  refreshing: boolean;
  headerHeight: number;      // 占位元素高度（导航栏高度 + 固定头部高度）
  navBarHeight: number;       // 导航栏高度（用于动态设置固定头部的top值）
  products: Product[];
  filteredProducts: Product[];
  stats: {
    totalCount: number;
    sellingCount: number;
    offShelfCount: number;
    soldOutCount: number;
    pendingAuditCount: number;
    auditApprovedCount: number;
    auditRejectedCount: number;
  };
  
  // 筛选和搜索
  activeStatus: string;
  auditFilter: string;
  searchKeyword: string;
  selectedProducts: number[];
  
  // 分页
  page: number;
  limit: number;
  hasMore: boolean;
  
  // 弹窗状态
  showPriceModal: boolean;
  showStockModal: boolean;
  editingProduct: Product | null;
  editingSku: any;
  editingSkuList: any[]; // 所有SKU列表
  selectedSkuIndex: number; // 当前选中的SKU索引
  
  // 表单数据
  priceForm: {
    marketPrice: string;
    regionPrice: string;
  };
  stockForm: {
    stockQuantity: string;
  };
}

Page({
  data: {
    hasLogin: false,
    loading: false,
    refreshing: false,
    headerHeight: 0,  // 占位元素高度（导航栏高度 + 固定头部高度）
    navBarHeight: 0,  // 导航栏高度（用于动态设置固定头部的top值）
    products: [],
    filteredProducts: [],
    stats: {
      totalCount: 0,
      sellingCount: 0,
      offShelfCount: 0,
      soldOutCount: 0,
      pendingAuditCount: 0,
      auditApprovedCount: 0,
      auditRejectedCount: 0
    },
    
    // 筛选和搜索
    activeStatus: '',
    auditFilter: '',
    searchKeyword: '',
    selectedProducts: [],
    
    // 分页
    page: 1,
    limit: 10,
    hasMore: true,
    
    // 弹窗状态
    showPriceModal: false,
    showStockModal: false,
    showDetailModal: false,
    editingProduct: null,
    detailProduct: null,
    editingSku: null,
    editingSkuList: [],
    selectedSkuIndex: 0,
    
    // 表单数据
    priceForm: {
      marketPrice: '',
      regionPrice: ''
    },
    stockForm: {
      stockQuantity: ''
    }
  } as ProductsPageData,

  onLoad() {
    this.checkLoginStatus();
    if (this.data.hasLogin) {
      this.loadProducts();
      this.loadProductStats();
      // 延迟计算头部高度，确保DOM已渲染
      setTimeout(() => {
        this.calculateHeaderHeight();
      }, 300);
    }
  },

  onReady() {
    if (this.data.hasLogin) {
      this.calculateHeaderHeight();
    }
  },

  onShow() {
    const wasLoggedIn = this.data.hasLogin;
    this.checkLoginStatus();
    // 如果从未登录变为已登录，需要加载数据和计算头部高度
    if (!wasLoggedIn && this.data.hasLogin) {
      this.loadProducts();
      this.loadProductStats();
      setTimeout(() => {
        this.calculateHeaderHeight();
      }, 300);
    }
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('merchantToken');
    const userInfo = wx.getStorageSync('merchantUserInfo');
    
    if (token && userInfo) {
      this.setData({
        hasLogin: true
      });
    } else {
      this.setData({
        hasLogin: false
      });
    }
  },

  // 去登录页
  goToLogin() {
    wx.navigateTo({
      url: '/pages/auth/auth'
    });
  },

  /**
   * 计算固定头部高度
   */
  calculateHeaderHeight() {
    // 使用setTimeout确保DOM已渲染
    setTimeout(() => {
      const query = wx.createSelectorQuery().in(this);
      // 同时获取导航栏和固定头部的高度
      query.select('#productsNavBar').boundingClientRect();
      query.select('.fixed-header').boundingClientRect();
      query.exec((res: any) => {
        const navBarRect = res?.[0];
        const fixedHeaderRect = res?.[1];

        const navBarHeight = navBarRect?.height || this.estimateNavBarHeight();
        const fixedHeaderHeight = fixedHeaderRect?.height || this.estimateFixedHeaderHeight();

        const safetyMargin = 12;

        if (navBarHeight && fixedHeaderHeight) {
          // 占位高度 = 导航栏高度 + 固定头部高度（因为两者都是fixed定位）
          const totalHeight = navBarHeight + fixedHeaderHeight + safetyMargin;

          console.log('计算头部高度:', {
            navBarHeight,
            fixedHeaderHeight,
            totalHeight
          });

          this.setData({
            headerHeight: totalHeight,
            navBarHeight
          });
        } else {
          const fallbackHeight = this.estimateFixedHeaderHeight() + this.estimateNavBarHeight() + safetyMargin;
          this.setData({
            headerHeight: fallbackHeight,
            navBarHeight: this.estimateNavBarHeight()
          });
        }
      });
    }, 200); // 增加延迟时间，确保DOM完全渲染
  },

  estimateNavBarHeight(): number {
    try {
      const menuRect = wx.getMenuButtonBoundingClientRect();
      const windowInfo = wx.getWindowInfo();
      const statusBarHeight = windowInfo.statusBarHeight || windowInfo.safeArea?.top || 0;
      const gap = menuRect.top - statusBarHeight;
      // 导航高度 = 状态栏高度 + 胶囊上下间距 + 胶囊高度
      return statusBarHeight + gap * 2 + menuRect.height;
    } catch (error) {
      console.warn('estimateNavBarHeight error', error);
      // iOS刘海 88px，普通机型 64px
      return 88;
    }
  },

  estimateFixedHeaderHeight(): number {
    // 统计区域约 150rpx ≈ 75px + 筛选区域约 150rpx ≈ 75px + 操作栏约 100rpx ≈ 50px + padding 40rpx ≈ 20px
    return 75 + 75 + 50 + 20;
  },

  /**
   * 加载商品列表
   */
  async loadProducts(isRefresh = false) {
    if (isRefresh) {
      this.setData({
        page: 1,
        products: [],
        filteredProducts: [],
        hasMore: true
      });
    }

    if (!this.data.hasMore && !isRefresh) {
      return;
    }

    this.setData({
      loading: true,
      refreshing: isRefresh
    });

    try {
      const params: any = {
        pageNum: this.data.page,
        pageSize: this.data.limit
      };

      if (this.data.activeStatus !== '') {
        params.status = Number(this.data.activeStatus);
      }
      if (this.data.auditFilter !== '') {
        params.auditStatus = Number(this.data.auditFilter);
      }
      if (this.data.searchKeyword.trim()) {
        params.name = this.data.searchKeyword.trim();
      }

      const response = await MerchantAPI.getProducts(params);
      const rows = response?.rows || response?.data?.rows || [];
      const totalValue = response?.total ?? response?.data?.total;

      const mapped = rows.map((item: any) => this.normalizeProduct(item));
      const products = isRefresh ? mapped : [...this.data.products, ...mapped];
      const hasMore = typeof totalValue === 'number'
        ? products.length < totalValue
        : rows.length >= this.data.limit;

      // 为每个商品添加isSelected标记
      const filteredProducts = this.addSelectedFlag(products);

      this.setData({
        products,
        filteredProducts,
        hasMore,
        page: this.data.page + 1
      });
      // 不在这里调用统计，统计应该只在初始化时调用一次
      if (isRefresh) {
        this.setData({ selectedProducts: [] });
      }
    } catch (error) {
      console.error('加载商品列表失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({
        loading: false,
        refreshing: false
      });
    }
  },


  normalizeProduct(item: any): Product {
    // 后端Product实体字段：status: 0-下架，1-上架，2-售罄
    // 如果status为null/undefined，根据库存判断：stockQuantity为0则为售罄(2)，否则为上架(1)
    let status: number;
    if (typeof item.status === 'number') {
      status = item.status;
    } else {
      const stockQuantity = Number(item.stockQuantity ?? item.stock ?? 0);
      status = stockQuantity === 0 ? 2 : 1; // 售罄或上架
    }
    const auditStatus = typeof item.auditStatus === 'number' ? item.auditStatus : 0;
    const auditStatusText = AUDIT_STATUS_TEXT_MAP[auditStatus] || '待审核';
    const canToggleStatus = auditStatus === 1;
    
    // 计算最低价格（从所有SKU中找最低价格）
    let minPrice = Number(item.regionPrice ?? item.price ?? 0);
    let totalStock = Number(item.stockQuantity ?? item.stock ?? 0);
    
    if (item.skuList && item.skuList.length > 0) {
      // 找到最低价格
      const prices = item.skuList.map((sku: any) => Number(sku.price ?? 0)).filter((p: number) => p > 0);
      if (prices.length > 0) {
        minPrice = Math.min(...prices);
      }
      
      // 计算总库存
      totalStock = item.skuList.reduce((sum: number, sku: any) => {
        return sum + Number(sku.stock ?? 0);
      }, 0);
      
      // 如果总库存为0，设置为售罄状态
      if (totalStock === 0 && status === 1) {
        status = 2;
      }
    }
    
    return {
      productId: item.productId || item.dishId || 0,
      productName: item.name || item.dishName || item.productName || '',
      imageUrl: item.imageUrl || item.images?.[0] || '/images/empty-messages.png',
      description: item.description || '',
      marketPrice: Number(item.marketPrice ?? 0),
      regionPrice: minPrice, // 使用最低价格
      stockQuantity: totalStock, // 使用总库存
      salesCount: Number(item.salesCount ?? 0),
      monthlySales: Number(item.monthlySales ?? item.salesCount ?? 0),
      status,
      statusText: STATUS_TEXT_MAP[status] || '未知状态',
      auditStatus,
      auditStatusText,
      categoryId: item.categoryId ?? 0,
      categoryName: item.categoryName || '',
      isHot: Boolean(item.isHot),
      isNew: Boolean(item.isNew),
      sortOrder: Number(item.sortOrder ?? 0),
      createdAt: item.createTime || item.createdAt || '',
      // 保存完整的后端数据，供后续使用
      skuList: item.skuList || [],
      specGroups: item.specGroups || [],
      // 标记是否有多个SKU，用于显示价格格式
      hasMultipleSkus: item.skuList && item.skuList.length > 1,
      // 解析规格分组，用于显示
      parsedSpecGroups: item.specGroups ? item.specGroups.map((group: any) => ({
        groupName: group.groupName || group.name || '',
        specOptions: (() => {
          if (Array.isArray(group.specOptions)) {
            return group.specOptions.map((opt: string) => (opt || '').trim()).filter(Boolean);
          }
          if (Array.isArray(group.options)) {
            return group.options.map((opt: string) => (opt || '').trim()).filter(Boolean);
          }
          if (group.externField1) {
            try {
              const parsed = JSON.parse(group.externField1);
              if (Array.isArray(parsed)) {
                return parsed.map((opt: string) => (opt || '').trim()).filter(Boolean);
              }
            } catch (error) {
              console.warn('规格选项解析失败', error);
            }
          }
          return [];
        })()
      })) : [],
      canToggleStatus
    } as Product & { 
      skuList?: any[]; 
      specGroups?: any[]; 
      hasMultipleSkus?: boolean;
      parsedSpecGroups?: Array<{ groupName: string; specOptions: string[] }>;
    };
  },

  async prepareSkuData(product: Product) {
    wx.showLoading({ title: '加载中...', mask: true });
    try {
      const res = await MerchantAPI.getProductDetail(product.productId);
      const detail = res?.data || {};
      
      // 后端Product实体包含：specGroups (List<ProductSpecGroup>) 和 skuList (List<ProductSpecDetail>)
      // ProductSpecDetail: { skuId, specItems, price, marketPrice, stock, ... }
      let skuList = detail.skuList || [];
      
      // 如果没有SKU列表，创建一个默认的SKU
      if (skuList.length === 0) {
        skuList = [{
          skuId: detail.skuId || product.productId,
          specItems: '默认',
          price: detail.regionPrice ?? product.regionPrice ?? 0,
          marketPrice: detail.marketPrice ?? product.marketPrice ?? 0,
          stock: detail.stockQuantity ?? product.stockQuantity ?? 0
        }];
      }
      
      // 标准化SKU数据，匹配后端ProductSpecDetail结构
      const normalizedSkuList = skuList.map((sku: any) => ({
        skuId: sku.skuId || sku.detailId || product.productId, // skuId是ProductSpecDetail的主键
        specItems: sku.specItems || '默认', // 规格项组合字符串
        price: Number(sku.price ?? sku.regionPrice ?? 0), // 售价
        marketPrice: Number(sku.marketPrice ?? sku.price ?? 0), // 市场价
        stock: Number(sku.stock ?? sku.stockQuantity ?? 0) // 库存
      }));

      const firstSku = normalizedSkuList[0] || {
        skuId: product.productId,
        specItems: '默认',
        price: product.regionPrice,
        marketPrice: product.marketPrice,
        stock: product.stockQuantity
      };

      this.setData({
        editingProduct: product,
        editingSku: firstSku,
        editingSkuList: normalizedSkuList,
        selectedSkuIndex: 0
      });
      return { sku: firstSku, skuList: normalizedSkuList };
    } catch (error) {
      console.error('获取商品详情失败', error);
      wx.showToast({
        title: '获取详情失败',
        icon: 'none'
      });
      throw error;
    } finally {
      wx.hideLoading();
    }
  },

  /**
   * 加载商品统计数据（获取所有商品进行统计）
   */
  async loadProductStats() {
    try {
      // 获取所有商品（不带任何筛选条件）
      const response = await MerchantAPI.getProducts({
        pageNum: 1,
        pageSize: 1000 // 获取足够多的商品用于统计
      });
      
      const allProducts = response?.rows || response?.data?.rows || [];
      console.log('📊 统计数据 - 总商品数:', allProducts.length);
      
      // 打印每个商品的状态和审核状态用于调试
      allProducts.forEach((p: any, index: number) => {
        if (index < 10) { // 打印前10个商品
          console.log(`商品${index + 1}: ${p.productName || p.name}, status=${p.status}, auditStatus=${p.auditStatus}`);
        }
      });
      
      // 使用兼容性更好的字段访问方式
      const getStatus = (p: any) => {
        const status = p.status ?? p.dishStatus ?? p.productStatus;
        return Number(status);
      };
      
      const getAuditStatus = (p: any) => {
        const auditStatus = p.auditStatus ?? p.audit_status;
        return Number(auditStatus);
      };
      
      // 关键修改：已下架/售卖中/已售罄的统计，只统计审核通过(auditStatus=1)的商品
      const stats = {
        totalCount: allProducts.length,
        // 售卖中：审核通过 且 status=1
        sellingCount: allProducts.filter((p: any) => getAuditStatus(p) === 1 && getStatus(p) === 1).length,
        // 已下架：审核通过 且 status=0
        offShelfCount: allProducts.filter((p: any) => getAuditStatus(p) === 1 && getStatus(p) === 0).length,
        // 已售罄：审核通过 且 status=2
        soldOutCount: allProducts.filter((p: any) => getAuditStatus(p) === 1 && getStatus(p) === 2).length,
        // 待审核：不管status，只看auditStatus=0
        pendingAuditCount: allProducts.filter((p: any) => getAuditStatus(p) === 0).length,
        // 已通过：auditStatus=1
        auditApprovedCount: allProducts.filter((p: any) => getAuditStatus(p) === 1).length,
        // 已拒绝：auditStatus=2
        auditRejectedCount: allProducts.filter((p: any) => getAuditStatus(p) === 2).length
      };
      
      console.log('📊 计算出的统计:', stats);
      console.log('详细统计:', {
        '售卖中(审核通过 且 status=1)': stats.sellingCount,
        '已下架(审核通过 且 status=0)': stats.offShelfCount,
        '已售罄(审核通过 且 status=2)': stats.soldOutCount,
        '待审核(auditStatus=0)': stats.pendingAuditCount,
        '已通过(auditStatus=1)': stats.auditApprovedCount,
        '已拒绝(auditStatus=2)': stats.auditRejectedCount
      });
      
      this.setData({ stats });
    } catch (error) {
      console.error('❌ 加载商品统计失败:', error);
    }
  },

  /**
   * 筛选商品
   */
  filterProducts() {
    this.setData({
      filteredProducts: this.data.products
    });
  },

  /**
   * 按状态和审核状态筛选（合并）
   */
  filterByStatusAndAudit(e: any) {
    const status = e.currentTarget.dataset.status;
    const audit = e.currentTarget.dataset.audit;
    
    // 关键逻辑：当筛选售卖中/已下架/已售罄时，自动添加auditStatus=1（审核通过）的条件
    // 只有筛选"全部"、"待审核"、"已拒绝"时才使用传入的audit参数
    let finalAuditFilter = audit;
    
    if (status !== '' && audit === '') {
      // 如果选择了具体的status（售卖中/已下架/已售罄），强制只显示审核通过的
      finalAuditFilter = '1';
    }
    
    this.setData({
      activeStatus: status,
      auditFilter: finalAuditFilter,
      selectedProducts: [],
      page: 1,
      hasMore: true
    });
    this.loadProducts(true);
  },

  /**
   * 按状态筛选
   */
  filterByStatus(e: any) {
    const status = e.currentTarget.dataset.status;
    this.setData({
      activeStatus: status,
      selectedProducts: [],
      page: 1,
      hasMore: true
    });
    this.loadProducts(true);
  },

  /**
   * 按审核状态筛选
   */
  filterByAuditStatus(e: any) {
    const status = e.currentTarget.dataset.status;
    this.setData({
      auditFilter: status,
      selectedProducts: [],
      page: 1,
      hasMore: true
    });
    this.loadProducts(true);
  },

  /**
   * 搜索输入
   */
  onSearchInput(e: any) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  onSearchConfirm() {
    this.setData({
      page: 1,
      hasMore: true
    });
    this.loadProducts(true);
  },

  /**
   * 清空搜索
   */
  clearSearch() {
    this.setData({
      searchKeyword: ''
    });
    this.loadProducts(true);
  },

  /**
   * 选择商品
   */
  toggleSelectProduct(e: any) {
    const productId = Number(e.currentTarget.dataset.id);
    const selectedProducts = [...this.data.selectedProducts];
    const index = selectedProducts.indexOf(productId);
    
    if (index >= 0) {
      // 已选中，则取消选中
      selectedProducts.splice(index, 1);
    } else {
      // 未选中，则添加
      selectedProducts.push(productId);
    }
    
    console.log('选中的商品ID列表:', selectedProducts);
    console.log('当前productId:', productId, '类型:', typeof productId);
    
    // 使用新的selectedProducts重新计算filteredProducts
    const filteredProducts = this.data.products.map(product => ({
      ...product,
      isSelected: selectedProducts.includes(Number(product.productId))
    }));
    
    console.log('更新后的filteredProducts:', filteredProducts.map(p => ({ id: p.productId, selected: p.isSelected })));
    
    this.setData({
      selectedProducts,
      filteredProducts
    });
  },

  // 为商品数据添加isSelected标记
  addSelectedFlag(products: any[]): any[] {
    const selectedProducts = this.data.selectedProducts;
    return products.map(product => ({
      ...product,
      isSelected: selectedProducts.includes(Number(product.productId))
    }));
  },

  /**
   * 批量操作
   */
  async batchOperation(e: any) {
    const operation = e.currentTarget.dataset.operation;
    const { selectedProducts } = this.data;
    
    if (selectedProducts.length === 0) {
      wx.showToast({
        title: '请先选择商品',
        icon: 'none'
      });
      return;
    }

    const invalid = this.data.products.filter(product => selectedProducts.includes(product.productId) && product.auditStatus !== 1);
    if (invalid.length > 0) {
      wx.showToast({
        title: '仅审核通过的商品可批量操作',
        icon: 'none'
      });
      return;
    }

    const operationText = operation === 'on_shelf' ? '上架' : '下架';
    const status = operation === 'on_shelf' ? 1 : 0;

    wx.showModal({
      title: '批量操作',
      content: `确定要批量${operationText}选中的${selectedProducts.length}个商品吗？`,
      success: async (res) => {
        if (res.confirm) {
          this.setData({ loading: true });

          try {
            await MerchantAPI.updateProductStatus({
              productIds: selectedProducts,
              status
            });

            wx.showToast({
              title: `批量${operationText}成功`,
              icon: 'success'
            });

            this.setData({ selectedProducts: [], page: 1, hasMore: true });
            this.loadProducts(true);
            this.loadProductStats();

          } catch (error) {
            wx.showToast({
              title: `批量${operationText}失败`,
              icon: 'none'
            });
          } finally {
            this.setData({ loading: false });
          }
        }
      }
    });
  },

  /**
   * 切换商品状态
   */
  async toggleProductStatus(e: any) {
    const product = e.currentTarget.dataset.product;
    if (!product) return;
    if (product.auditStatus !== 1) {
      wx.showToast({
        title: '审核通过后才能操作',
        icon: 'none'
      });
      return;
    }
    const newStatus = product.status === 1 ? 0 : 1;
    const statusText = newStatus === 1 ? '上架' : '下架';

    try {
      await MerchantAPI.updateProductStatus({
        productIds: [product.productId],
        status: newStatus
      });

      wx.showToast({
        title: `商品已${statusText}`,
        icon: 'success'
      });

      this.setData({ page: 1, hasMore: true });
      this.loadProducts(true);
      this.loadProductStats();
    } catch (error) {
      console.error('更新状态失败', error);
      wx.showToast({
        title: `${statusText}失败`,
        icon: 'none'
      });
    }
  },

  /**
   * 编辑价格
   */
  async editPrice(e: any) {
    const product = e.currentTarget.dataset.product;
    if (!product) return;
    try {
      const { sku, skuList } = await this.prepareSkuData(product);
      this.setData({
        showPriceModal: true,
        priceForm: {
          marketPrice: sku.marketPrice != null ? String(sku.marketPrice) : '',
          regionPrice: sku.price != null ? String(sku.price) : ''
        },
        editingSkuList: skuList,
        selectedSkuIndex: 0
      });
    } catch (error) {
      // 已在 prepareSkuData 中提示
    }
  },

  selectSkuForPrice(e: any) {
    const index = e.currentTarget.dataset.index;
    const sku = this.data.editingSkuList[index];
    if (sku) {
      this.setData({
        selectedSkuIndex: index,
        editingSku: sku,
        priceForm: {
          marketPrice: sku.marketPrice != null ? String(sku.marketPrice) : '',
          regionPrice: sku.price != null ? String(sku.price) : ''
        }
      });
    }
  },

  /**
   * 编辑库存
   */
  async editStock(e: any) {
    const product = e.currentTarget.dataset.product;
    if (!product) return;
    try {
      const { sku, skuList } = await this.prepareSkuData(product);
      this.setData({
        showStockModal: true,
        stockForm: {
          stockQuantity: sku.stock != null ? String(sku.stock) : ''
        },
        editingSkuList: skuList,
        selectedSkuIndex: 0
      });
    } catch (error) {
      // 已提示
    }
  },

  selectSkuForStock(e: any) {
    const index = e.currentTarget.dataset.index;
    const sku = this.data.editingSkuList[index];
    if (sku) {
      this.setData({
        selectedSkuIndex: index,
        editingSku: sku,
        stockForm: {
          stockQuantity: sku.stock != null ? String(sku.stock) : ''
        }
      });
    }
  },

  /**
   * 保存价格
   */
  async savePrice() {
    const { editingSku, priceForm } = this.data;
    if (!editingSku) {
      wx.showToast({ title: '未找到SKU信息', icon: 'none' });
      return;
    }

    const marketPrice = parseFloat(priceForm.marketPrice);
    const regionPrice = parseFloat(priceForm.regionPrice);
    const stock = Number(editingSku.stock ?? 0);
    
    if (isNaN(regionPrice) || regionPrice <= 0) {
      wx.showToast({
        title: '请输入正确的售价',
        icon: 'none'
      });
      return;
    }
    
    if (isNaN(marketPrice) || marketPrice <= 0) {
      wx.showToast({
        title: '请输入正确的市场价',
        icon: 'none'
      });
      return;
    }
    
    this.setData({ loading: true });

    try {
      // 匹配后端SkuPriceStockUpdateDTO格式：{ skuId: Long, price: BigDecimal, stock: Integer, marketPrice?: BigDecimal }
      await MerchantAPI.updateProductPriceStock({
        skuId: editingSku.skuId, // SKU ID (Long类型)
        price: regionPrice, // 售价 (BigDecimal)
        marketPrice: marketPrice, // 市场价 (BigDecimal，可选)
        stock: stock >= 0 ? stock : 0 // 库存 (Integer)
      });

      this.setData({
        showPriceModal: false
      });

      wx.showToast({
        title: '价格更新成功',
        icon: 'success'
      });

      this.setData({ page: 1, hasMore: true });
      this.loadProducts(true);
      this.loadProductStats();
    } catch (error) {
      wx.showToast({
        title: '价格更新失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 保存库存
   */
  async saveStock() {
    const { editingSku, stockForm } = this.data;
    if (!editingSku) {
      wx.showToast({ title: '未找到SKU信息', icon: 'none' });
      return;
    }

    const stockQuantity = parseInt(stockForm.stockQuantity);
    const price = Number(editingSku.price ?? 0);
    const marketPrice = Number(editingSku.marketPrice ?? price);

    if (isNaN(stockQuantity) || stockQuantity < 0) {
      wx.showToast({
        title: '请输入正确的库存数量',
        icon: 'none'
      });
      return;
    }

    this.setData({ loading: true });

    try {
      // 匹配后端SkuPriceStockUpdateDTO格式：{ skuId: Long, price: BigDecimal, stock: Integer, marketPrice?: BigDecimal }
      await MerchantAPI.updateProductPriceStock({
        skuId: editingSku.skuId, // SKU ID (Long类型)
        price: price > 0 ? price : 0.01, // 售价 (BigDecimal)
        marketPrice: marketPrice > 0 ? marketPrice : price, // 市场价 (BigDecimal，可选)
        stock: stockQuantity // 库存 (Integer)
      });

      this.setData({
        showStockModal: false
      });

      wx.showToast({
        title: '库存更新成功',
        icon: 'success'
      });

      this.setData({ page: 1, hasMore: true });
      this.loadProducts(true);
      this.loadProductStats();
    } catch (error) {
      wx.showToast({
        title: '库存更新失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 查看商品详情
   */
  async viewProductDetail(e: any) {
    const product = e.currentTarget.dataset.product;
    if (!product || !product.productId) return;
    
    wx.showLoading({ title: '加载中...' });
    
    try {
      const response = await MerchantAPI.getProductDetail(product.productId);
      const data = response?.data || response;
      
      console.log('商品详情:', data);
      
      // 解析规格组
      const parsedSpecGroups = (data.specGroups || []).map((group: any) => {
        let specOptions: string[] = [];
        
        if (group.externField1) {
          try {
            specOptions = JSON.parse(group.externField1);
          } catch (e) {
            console.error('规格解析失败:', e);
          }
        }
        
        return {
          groupName: group.groupName,
          specOptions: specOptions
        };
      });
      
      this.setData({
        showDetailModal: true,
        detailProduct: {
          ...data,
          parsedSpecGroups
        }
      });
    } catch (error) {
      console.error('获取商品详情失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  /**
   * 关闭商品详情弹窗
   */
  closeDetailModal() {
    this.setData({
      showDetailModal: false,
      detailProduct: null
    });
  },

  /**
   * 添加商品
   */
  addProduct() {
    wx.navigateTo({
      url: '/pages/product-form/product-form?mode=create'
    });
  },

  /**
   * 编辑商品信息（重新提交审核）
   */
  editProductInfo(e: any) {
    const product = e.currentTarget.dataset.product;
    if (!product) return;
    wx.navigateTo({
      url: `/pages/product-form/product-form?mode=edit&productId=${product.productId}`
    });
  },

  /**
   * 下拉刷新
   */
  onRefresh() {
    this.loadProducts(true);
    this.loadProductStats();
  },

  /**
   * 加载更多
   */
  loadMore() {
    if (!this.data.loading && this.data.hasMore) {
      this.loadProducts();
    }
  },

  // 表单输入处理
  onMarketPriceInput(e: any) {
    this.setData({
      'priceForm.marketPrice': e.detail.value
    });
  },

  onRegionPriceInput(e: any) {
    this.setData({
      'priceForm.regionPrice': e.detail.value
    });
  },

  onStockInput(e: any) {
    this.setData({
      'stockForm.stockQuantity': e.detail.value
    });
  },

  // 弹窗控制
  closePriceModal() {
    this.setData({
      showPriceModal: false
    });
  },

  closeStockModal() {
    this.setData({
      showStockModal: false
    });
  },

  preventClose() {
    // 阻止事件冒泡
  }
});

